package com.pi.pro.xcmg.am.was.edi.mes.fac;

import com.pi.common.utils.TextUtils;
import com.pi.pro.xcmg.am.common.vo.edi.ComponentItem;
import com.pi.pro.xcmg.am.common.vo.edi.KitDocumentReplyData;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析SOAP文件
 */
@Component
public class XPathSoapParser {

    // 预编译DocumentBuilderFactory以提高性能
    private static final DocumentBuilderFactory factory = createDocumentBuilderFactory();
    static {
        // 初始化DocumentBuilderFactory
        try {
            factory.setNamespaceAware(false);
            factory.setIgnoringElementContentWhitespace(true);
            // JDK8安全特性设置
            try {
                factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            } catch (Exception e) {
                // 忽略不支持的特性
            }
        } catch (Exception e) {
            // 初始化异常处理
        }
    }

    private static DocumentBuilderFactory createDocumentBuilderFactory() {
        return DocumentBuilderFactory.newInstance();
    }


    /**
     * 解析SOAP响应中的ComponentItem对象
     * @param soapResponse SOAP响应字符串
     * @return ComponentItem对象列表
     * @throws Exception 解析异常
     */
    public List<ComponentItem> parseMaterial(String soapResponse) throws Exception {
        List<ComponentItem> items = new ArrayList<>();

        try {
            // JDK8兼容的DocumentBuilder创建方式
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(soapResponse.getBytes("UTF-8")));

            // 获取所有ComponentItem节点
            NodeList itemNodes = document.getElementsByTagName("ComponentItem");

            // 预分配容量以提高性能
            int initialCapacity = Math.min(itemNodes.getLength(), 1000); // 设置合理上限
            items = new ArrayList<ComponentItem>(initialCapacity);

            // 解析每个ComponentItem节点
            for (int i = 0; i < itemNodes.getLength(); i++) {
                Element itemElement = (Element) itemNodes.item(i);
                ComponentItem item = new ComponentItem();

                // 提取字段数据
                item.setCOMPNO(getElementText(itemElement, "COMPNO"));
                item.setCOMPNAME(getElementText(itemElement, "COMPNAME"));
                item.setUNIT(getElementText(itemElement, "UNIT"));
                item.setRSVFIELDB(getElementText(itemElement, "RSVFIELDB"));
                item.setMRPOWNER(getElementText(itemElement, "MRPOWNER"));
                item.setIDLEMARK(getElementText(itemElement, "IDLEMARK"));
                item.setRSVFIELD1(getElementText(itemElement, "RSVFIELD1"));
                item.setRSVFIELDC(getElementText(itemElement, "RSVFIELDC"));
                item.setZPSLX(getElementText(itemElement, "ZPSLX"));
                item.setPRDGroup(getElementText(itemElement, "PRDGroup"));
                item.setZDENGDAO(getElementText(itemElement, "PRDGroup"));
                items.add(item);
            }
        } catch (Exception e) {
            System.err.println("解析SOAP响应失败: " + e.getMessage());
            throw e;
        }
        return items;
    }


    /**
     * 解析SOAP响应中的ComponentItem对象
     * @param soapResponse SOAP响应字符串
     * @return ComponentItem对象列表
     * @throws Exception 解析异常
     */
    public KitDocumentReplyData parseDocuemnt(String soapResponse) throws Exception {
        KitDocumentReplyData doc = null;

        String datatext="";
        try {
            doc= TextUtils.toObject(datatext, KitDocumentReplyData.class);
        } catch (Exception e) {
            System.err.println("解析SOAP响应失败: " + e.getMessage());
            throw e;
        }
        return doc;
    }


    /**
     * 获取元素的文本内容
     * JDK8兼容版本
     * @param parent 父元素
     * @param tagName 标签名
     * @return 文本内容
     */
    private String getElementText(Element parent, String tagName) {
        NodeList nodes = parent.getElementsByTagName(tagName);
        if (nodes != null && nodes.getLength() > 0) {
            Node node = nodes.item(0);
            if (node != null) {
                // JDK8兼容的文本获取方式
                NodeList childNodes = node.getChildNodes();
                if (childNodes != null) {
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node child = childNodes.item(i);
                        if (child.getNodeType() == Node.TEXT_NODE) {
                            return child.getNodeValue();
                        }
                    }
                }
            }
        }
        return null;
    }
}
